package Cantella::DJabberd::Plugin::Delivery;

use strict;
use warnings;

use base 'DJabberd::Delivery';

use DJabberd::Log;
use DateTime;

our $logger = DJabberd::Log->get_logger;
sub log { $logger }

#config variables
sub set_config_schema {
  my ($self, $schema) = @_;
  #type check here?
  $self->{dbic_schema} = $schema;
}

sub set_config_dsn {
  my ($self, $dbdsn) = @_;
  $self->{dbic_dbdsn} = $dbdsn;
}

sub set_config_dbusername {
  my ($self, $dbusername) = @_;
  $self->{dbic_dbusername} = $dbusername;
}

sub set_config_dbpassword {
  my ($self, $dbpassword) = @_;
  $self->{dbic_dbpassword} = $dbpassword;
}

sub set_config_schemaclass {
  my ($self, $schema_class) = @_;
  $self->{dbic_schema_class} = $schema_class;
}

#Throw exceptions if all our data is not provided.
sub finalize {
  my $self = shift;

  return if eval { $self->{dbic_schema}->isa('DBIx::Class::Schema') };

  $logger->fatal("dsn not provided")      unless $self->{dbic_dbdsn};
  $logger->fatal("username not provided") unless $self->{dbic_dbusername};
  $logger->fatal("password not provided") unless $self->{dbic_dbpassword};

  my $schema = $self->{dbic_schema_class}->connect(
                                                 $self->{dbic_dbdsn},
                                                 $self->{dbic_dbusername},
                                                 $self->{dbic_dbpassword}
                                                );
  #warn("Successfully logged in to the database") if $schema;
  $logger->fatal("Could not connect to the database") unless $schema;
  $self->{dbic_schema} = $schema;
}

sub get_jid {
  my ($self,$jid) = @_;
  my $rs = $self->{dbic_schema}->resultset('UserJid')->search
    ( 
     { node => $jid->node, 'domain.hostname' => $jid->domain },
     { join => ['domain'], },
    );
  if(my $jid = $rs->first){
    return $jid;
  }
  return;
}

sub deliver {
  my ($self, $vhost, $cb, $stanza) = @_;
  return $cb->declined unless $stanza->element_name eq 'message';

  my $to = $self->get_jid($stanza->to_jid);
  my $form = $self->get_jid($stanza->from_jid);
  my @bodies = grep { $_->element_name eq "body" } $stanza->children_elements;
  return unless @bodies;

  my $rs = $self->{dbic_schema}->resultset('LoggedMessage');
  for my $body (@bodies){
    my $text = $body->first_child or next;
    $rs->create( { to => $to, from => $from, message => $text})
    $logger->info("Logged message from $from to $to with body '$text'");
  }

  #decline the delivery so that it goes to the other hooks too
  return $cb->declined
}

1;
